let express = require('express')
let router = express.Router()

let bodyParser = require('body-parser')
let Mock = require('mockjs')
let temp = require('../assets/function')
let data = require('../db/data')

// 添加数据(1)
router.post('/add1', (req, res) => {
    let num = req.query
    for (let i in data) {
        if (data[i].id != num.id) {
            data.unshift(temp(num))
            res.json(data)
            return
        } else {
            res.json({
                message: "数据重复"
            })
            return
        }
    }
})
// 添加数据(2)
router.post('/add2', (req, res) => {
    let num = req.query
    data.unshift(temp(num))
    res.json(data)
})

// 编辑与修改1
router.post('/add3', (req, res) => {
    let num = req.query
    // 当id有值，编辑
    if (num.id) {
        for (let i in data) {
            if (data[i].id == num.id) {
                data.splice(i, 1, temp(num,data[i]))
                res.json(data)
                return
            } else {
                res.json({ message: "传参错误"})
                return
            }
        }

    } else {
        // 当id没有值，添加
        for (let i in data) {
            if (data[i].id != temp(num).id) {
                data.unshift(temp(num))
                res.json(data)
                return
            } else {
                res.json({
                    message: "error"
                })
                return
            }
        }
    }

})


//编辑与添加2
router.post('/change',(req,res)=>{
    let num = req.query
    if(num.id){
        for(let i in data){
            if(data[i].id == num.id){
                data.splice(i,1,temp(num,data[i]))
                res.json(data)
                return
            }else {
                res.json({message:"参数错误"})
            }
        }   
    }else {
        data.unshift(temp(num))
        res.json(data)
        return
    }
    
})






module.exports = router